#include <json/json.h>
#include <memory>
#include <iostream>
#include <sstream>

bool Serialize(const Json::Value& val,std::string& result)
{
    //1.先定义Json::StreamWriter 的工厂类 Json::StreamWriterBuilder
    Json::StreamWriterBuilder swb;
    //2.定义序列化对象
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    //3.通过Json::StreamWriter中的write接口进行序列化
    std::stringstream ss;
    int ret = sw->write(val,&ss);
    if(ret != 0)
    {
        std::cout << "Json序列化失败" << std::endl;
        return false;
    }
    result = ss.str();
    return true;
}

bool Deserialize(const std::string& src,Json::Value& val)
{
    //1.先定义Json:: CharReader 的工厂类Json::CharReaderBuilder工厂类
    Json::CharReaderBuilder crb;
    //2.定义反序列化对象
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    std::string err;
    bool ret = cr->parse(src.c_str(),src.c_str()+src.size(),&val,&err);
    if(ret == false)
    {
        std::cout << "Json反序列化失败" << err << std::endl;
        return false;
    }
    return true;
}

int main()
{
    char name[] = "张三";
    int age = 18;
    float score[3] = {88,99,55};

    Json::Value stu;
    stu["name"] = name;
    stu["age"] = age;

    stu["score"].append(score[0]);
    stu["score"].append(score[1]);
    stu["score"].append(score[2]);

    //序列化
    std::string stu_str;
    int ret = Serialize(stu,stu_str);
    if(ret == false)
        return -1;
    std::cout << stu_str << std::endl;


    //反序列化
    Json::Value val;
    ret = Deserialize(stu_str,val);
    if(ret == false)
        return -1;
    std::cout << val["name"].asString() << std::endl;
    std::cout << val["age"].asInt() << std::endl;
    int sz = val["score"].size();
    for(int i = 0; i < sz; ++i)
    {
        std::cout << val["score"][i].asFloat() << std::endl;
    }
    return 0;
}